// key 高德申请key
// &plugin=AMap.DistrictSearch 高亮省份，市区使用。
// if ('addEventListener' in document) {
// 	document.addEventListener('DOMContentLoaded', function() {
// 		FastClick.attach(document.body);
// 	}, false);
// }
var nowPoint = null
var map = null
var marker1 = null
var vue = new Vue({
    el: "#main",
    data() {
        return {
            tagList: [], //标签分类
            ruleForm: {
                is_small_place: '',
                is_cater: '',
                placeDetail: '',
                remark: '',
                link_man_info: [{
                    name: '',
                    phone: '',
                }],
                place_name: '',
                address: '',
                longitude: '',
                latitude: '',
                category_id: '',
                images: [],
                first_tags: "",
                tags: [],
                grids_id: ''
            },
            isManual: false,
            placeList: [],
            addNote: false,
            location: '',
            loading: false,
            userInfo: userInfo,
            temp: {
                remark: '',
                place_id: '',
                images: []
            },
            imagesList: [],
            newRemark: '',
            noteList: [],
            prompt: false,
            msg: '',
            rules: {
                phone: [{
                    required: true,
                    message: '请核联系人电话',
                    pattern: /^1[3-9][0-9]{9}$/,
                    trigger: 'blur'
                }],
                contacts: [{
                    required: true,
                    message: '请输入联系人信息',
                    trigger: 'blur'
                }],
                category_id: [{
                    required: true,
                    message: '请选择场所分类',
                    trigger: 'change'
                }],
                place_name: [{
                    required: true,
                    message: '请输入场所名称',
                    trigger: 'blur'
                }, ],
                // content: [{
                //     required: true,
                //     message: '请输入情况说明',
                //     trigger: 'change'
                // }],
                address: [{
                    required: true,
                    message: '请输入场所地址信息',
                    trigger: 'change'
                }],
                is_small_place: [{
                    required: true,
                    message: '请选择是否为九小场所',
                    trigger: 'change'
                }],
                is_cater: [{
                    required: true,
                    message: '请选择是否涉餐饮',
                    trigger: 'change'
                }],
                first_tags: [{
                    required: true,
                    message: '请选择场所主标签',
                    trigger: 'change'
                }],
                // grids_id: [{
                //     required: true,
                //     message: '请选择网格',
                //     trigger: 'change'
                // }]
            },
            additionalObj: {},
            additionalList: [],
            locationList: [],
            map: null,
            isUploadImg: true,
            imgNumber: 9,
            noteImgNumber: 9,
            isUploadNoteImg: true,
            isUploadLoading: false,
            time: null,
            communityValue: [],
            communityInformation: []
        }
    },
    created() {
        this.getTags();
        this.getGrid()
    },
    mounted() {
        this.getPlaceList()
        // this.getAdditional()
        // this.getMap()
    },
    methods: {
        // 获取场所
        getTags() {
            ajax({
                url: formal + '/place/tags',
                type: 'GET',
                success: (res) => {
                    this.tagList = res.data.list
                }
            })
        },
        // 确定中心点经纬度按钮
        confirmLocation() {
            this.isManual = false
            this.ruleForm.latitude = nowPoint[1]; // 纬度，浮点数，范围为90 ~ -90
            this.ruleForm.longitude = nowPoint[0]; // 经度，浮点数，范围为180 ~ -180。
            this.location = "经度:" + this.ruleForm.longitude + "   纬度:" + this.ruleForm.latitude
        },
        // 调用微信sdk-wx.getLocation获取当前位置
        getLocation() {
            this.isManual = true
            // 获取当前位置
            wx.getLocation({
                isHighAccuracy: true,
                type: 'gcj02', // 默认为wgs84的 gps 坐标，如果要返回直接给 openLocation 用的火星坐标，可传入'gcj02'
                complete: (res) => {
                    this.ruleForm.latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                    this.ruleForm.longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                    var speed = res.speed; // 速度，以米/每秒计
                    var accuracy = res.accuracy; // 位置精度
                    let currentData = gcj02ToWgs(res.longitude, res.latitude)
                    this.location = "经度:" + currentData[0] + "   纬度:" + currentData[1]
                    this.locationList.push(res.longitude, res.latitude)
                    this.getMap(currentData)
                },
            });
        },
        // 判断当前位置是否有图标，有就清除
        removeMarker() {
            if (marker1 != null) {
                map.removeOverLay(marker1);
                marker1 = null
            }
        },
        // 跳转到当前位置，给当前位置添加点标注
        goCurrent() {
            if (this.time) {
                clearTimeout(this.time)
            }
            this.time = setTimeout(() => {
                this.removeMarker()
                wx.getLocation({
                    isHighAccuracy: true,
                    type: 'gcj02', // 默认为wgs84的 gps 坐标，如果要返回直接给 openLocation 用的火星坐标，可传入'gcj02'
                    complete: (res) => {
                        let currentData = gcj02ToWgs(res.longitude, res.latitude)
                        //创建图片对象
                        var icon = new T.Icon({
                            iconUrl: "../images/coordinates.png",
                            iconSize: new T.Point(25, 25),
                            // iconAnchor: new T.Point(10, 25)
                        });
                        marker1 = null
                        marker1 = new T.Marker(new T.LngLat(currentData[0], currentData[
                            1]), {
                            icon: icon
                        });
                        map.addOverLay(marker1);
                        map.centerAndZoom(new T.LngLat(currentData[0], currentData[1]),
                            18);
                    },
                });
            }, 500)
        },
        // 获取当前中心点位置+地图移动事件
        getMap(res) {
            nowPoint = res
            //初始化地图对象
            if (map == null) {
                map = new T.Map("container");
            }
            //设置显示地图的中心点和级别
            map.centerAndZoom(new T.LngLat(res[0], res[1]), 18);
            map.setMinZoom(11);
            map.setMaxZoom(18);
            map.addEventListener("moveend", function (e) {
                nowPoint = [map.getCenter().getLng(), map.getCenter().getLat()]
            })
        },
        // 选择场所change事件
        getValue(id) {
            for (var i in this.additionalObj) {
                if (id == i) {
                    this.additionalList = this.additionalObj[i]
                }
            }
            // this.additionalList.map(item => {
            // 	let field_name = item.field_name
            // 	// this.rules[field_name] = [{required: false,message: item.hint,trigger: 'blur'}]
            // 	// this.$set(this.rules,field_name, [{required: false,message: item.hint,trigger: 'blur'}])
            // })
        },
        // 附加字段
        getAdditional() {
            ajax({
                url: formal + '/place/get-place-fields',
                type: 'GET',
                success: (res) => {
                    this.additionalObj = res.data
                }
            })
        },
        // 个人信息接口
        getUserInfo() {
            ajax({
                url: formal + '/person/info',
                type: 'GET',
                success: (res) => {
                    localStorage.setItem("userInfo", JSON.stringify(res.data))
                    window.location.href = 'placeManagement.html'
                }
            })
        },
        // 删除备注图片
        deleteNoteImage(index) {
            this.imagesList.splice(index, 1)
            this.noteImgNumber = 9 - this.imagesList.length
            this.isUploadNoteImg = true
        },
        // 删除新增图片
        deleteImage(index) {
            this.ruleForm.images.splice(index, 1)
            this.imgNumber = 9 - this.ruleForm.images.length
            this.isUploadImg = true
        },
        // 删除备注
        deleteNote(index) {
            this.noteList.splice(index, 1)
        },
        // 删除联系人
        deleteContactPerson(index) {
            this.ruleForm.link_man_info.splice(index, 1)
        },
        // 查看图片
        lookImg(list) {
            wx.previewImage({
                // current: 'http://admin.tangshan.youbo.me/upload/place/202211/7WBay02UiZx9mszwLJcjoEgrX5GYhPTV.jpg', // 当前显示图片的 http 链接
                urls: list // 需要预览的图片 http 链接列表
            });
        },
        // 备注完成方法
        noteOut() {
            var tempObj = {
                remark: this.newRemark,
                place_id: '',
                images: this.imagesList
            }
            this.noteImgNumber = 9
            this.isUploadNoteImg = true
            if (this.newRemark == "" && this.imagesList.length == 0) {
                this.addNote = false
            } else {
                this.noteList.push(tempObj)
                this.addNote = false
            }
            this.newRemark = ''
            this.imagesList = []
        },
        // 提示弹窗
        goPlaceMan() {
            if (this.msg == "新增成功") {
                this.prompt = false
                this.getUserInfo()
            } else {
                this.prompt = false
            }
            this.loading = false
        },
        // 新增成功时，添加新增备注
        noteBtn(id) {
            this.noteList.map(item => {
                item.place_id = id
                ajax({
                    url: formal + '/place/add-remark',
                    type: 'POST',
                    data: item,
                    success: (res) => {
                        this.loading = false
                        this.prompt = true
                        // window.location.href = "placeManagement.html"
                    },
                    error: (res) => {
                        this.msg = res.message
                        this.prompt = true
                        this.loading = false
                    }
                })
            })
        },
        // 场所分类列表
        getPlaceList() {
            ajax({
                url: formal + '/place/category',
                type: 'GET',
                success: (res) => {
                    this.placeList = res.data.list
                }
            })
        },
        // 新增场所方法
        addPlace(formName) {
            console.log(this.ruleForm);
            // return;
            if (nowPoint != null) {
                let gaodeList = wgs84Togcj02(nowPoint[0], nowPoint[1])
                this.ruleForm.longitude = gaodeList[0]
                this.ruleForm.latitude = gaodeList[1]
            }
            this.loading = true
            if (this.ruleForm.place_name == "") {
                this.prompt = true
                this.loading = false
                this.msg = '请输入场所名称'
                return
            } else if (this.ruleForm.category_id == "") {
                this.prompt = true
                this.loading = false
                this.msg = '请选择场所分类'
                return
            } else if (this.ruleForm.is_small_place === '') {
                this.prompt = true
                this.loading = false
                this.msg = '请选择是否为九小场所'
                return
            } else if (this.ruleForm.is_cater === '') {
                this.prompt = true
                this.loading = false
                this.msg = '请选择是否涉餐饮'
                return
            } else if (this.ruleForm.link_man_info.length == 0) {
                this.prompt = true
                this.loading = false
                this.msg = '请填写联系人信息'
                return
            }
            // else if (this.ruleForm.link_man_info.length == 0) {
            //     this.prompt = true
            //     this.loading = false
            //     this.msg = '请填写基本情况说明'
            //     return
            // }
            else if (this.ruleForm.address == "") {
                this.prompt = true
                this.loading = false
                this.msg = '请输入场所地址信息'
                return
            }
            // else if (this.ruleForm.grids_id == "") {
            //     this.prompt = true
            //     this.loading = false
            //     this.msg = '请选择网格'
            //     return
            // }
            else if (this.ruleForm.first_tags == "") {
                this.prompt = true
                this.loading = false
                this.msg = '请选择场所主标签'
                return
            } else {
                this.ruleForm.link_man_info.map(item => {
                    if (item.name == "") {
                        this.prompt = true
                        this.loading = false
                        this.msg = '请输入联系人姓名'
                        return
                    }
                    if (item.phone == "") {
                        this.prompt = true
                        this.loading = false
                        this.msg = '请输入联系人手机号'
                        return
                    }
                    if (!/^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(item.phone)) {
                        this.prompt = true
                        this.loading = false
                        this.msg = '请输入正确的手机格式'
                        return
                    }
                })
            }
            for (var i = 0; i < this.additionalList.length; i++) {
                let fieldName = this.ruleForm[this.additionalList[i].field_name]
                if (fieldName === "") {
                    this.msg = this.additionalList[i].hint
                    this.prompt = true
                    this.loading = false
                    return
                } else if (fieldName === undefined) {
                    this.msg = this.additionalList[i].hint
                    this.prompt = true
                    this.loading = false
                    return
                }
            }
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    ajax({
                        url: formal + '/place/add-place',
                        type: "POST",
                        data: this.ruleForm,
                        success: (res) => {
                            this.msg = res.message
                            this.prompt = true
                            this.noteBtn(res.data.place_id)
                        }
                    })
                } else {
                    this.loading = false
                }
            });

        },
        // 新增联系人
        addPrincipal() {
            let obj = {
                name: '',
                phone: ''
            }
            this.ruleForm.link_man_info.push(obj)
        },
        // 上传图片判断上传长度，判断图片上传or备注图片上传
        uploadImageBtn(type) {
            let imgNum = null
            if (type == 1) {
                this.imgNumber = 9 - this.ruleForm.images.length
                if (this.imgNumber == 0) {
                    this.isUploadImg = false
                }
                imgNum = this.imgNumber
            } else if (type == 2) {
                this.noteImgNumber = 9 - this.imagesList.length
                if (this.noteImgNumber == 0) {
                    this.isUploadNoteImg = false
                }
                imgNum = this.noteImgNumber
            }
            wx.ready(() => {
                wx.chooseImage({
                    count: imgNum, // 默认9
                    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
                    success: (res) => {
                        var localIds = res
                            .localIds; // 返回选定照片的本地 ID 列表，localId可以作为 img 标签的 src 属性显示图片
                        this.uploadImg(localIds, type);
                    }
                })
            })
        },
        // 多图上传，判断上传长度执行回调
        uploadImg(localIds, type) {
            this.isUploadLoading = true
            var localId = localIds.shift();
            wx.uploadImage({
                localId: localId, // 需要上传的图片的本地ID，由 chooseImage 接口获得
                isShowProgressTips: 0, // 默认为1，显示进度提示
                success: (res) => {
                    var serverId = res.serverId; // 返回图片的服务器端ID
                    this.downloadImg(serverId, type)
                    if (localIds.length > 0) {
                        this.uploadImg(localIds, type)
                    }
                }
            })
        },
        // 上传成功后调取接口，获取图片地址做展示
        downloadImg(serverId, type) {
            ajax({
                url: formal + '/files/get-wx-media',
                type: 'POST',
                async: false,
                data: {
                    mediaId: serverId
                },
                success: (res) => {
                    if (res.status == 1) {
                        if (type == 1 && this.ruleForm.images.length <= 8) {
                            this.ruleForm.images.push(res.data.url)
                            this.imgNumber = 9 - this.ruleForm.images.length
                            if (this.imgNumber == 0) {
                                this.isUploadImg = false
                            }
                            this.isUploadLoading = false
                        } else if (type == 2 && this.imagesList.length <= 8) {
                            this.imagesList.push(res.data.url)
                            this.noteImgNumber = 9 - this.imagesList.length
                            if (this.noteImgNumber == 0) {
                                this.isUploadNoteImg = false
                            }
                            this.isUploadLoading = false
                        }
                    }
                }
            })
        },
        handleChange(value) {
            this.ruleForm.grids_id = value.pop();
        },
        // 获取网格
        getGrid() {
            ajax({
                url: formal + '/place/get-grids-fields',
                type: 'GET',
                success: (res) => {
                    this.communityInformation = res.data;
                }
            })
        }
    }
})